local desc_hx__1v3 = [[
  # 虎牢关2022简介
  ______________________

  对在2022年昙花一现于十周年服的变种虎牢关模式进行了魔改，原名是“三英战吕布”，还是熟悉的二、三、四号位选择武将作为联军，一号位固定为“吕布”，不同的是所有玩家都有当“吕布”的机会。“吕布”将以下面的吕布作为副将，体力固定为10，信息如下：


  性别：男     体力：10/10      势力：群     初始手牌：8

  技能：

  霸关：锁定技，你的延时类锦囊一定判定失败，你不会被翻面。你的摸牌阶段额外摸3张牌。

  武威：你使用【杀】或【决斗】可以额外指定两个目标。你的出牌阶段可以多使用两张【杀】。

  惊虎：锁定技，你使用【杀】或伤害类锦囊结算完毕后，若只对一个其他角色造成了伤害，该角色再失去1点体力。

  健驹：锁定技，你与其他角色的距离视为1。第三轮你的回合结束后，你撤离战场。

  ## 显而易见，三轮后游戏就会结束，故：

  ## 核心机制：

  联军阵亡时若仍有联军在场则改为休整一轮。

  ## 注意，本模式为PVP模式！（开启双将为“吕布”获得技能【再临】锁定技，首轮开始时，你执行额外的回合。）

  ## 吕布胜利条件：

  使三名联军同时处于休整状态。或联军累计阵亡5次。

  ## 联军胜利条件：

  三轮内击败吕布或吕布阵亡。联军一回合内未全部处于休整状态，且累计阵亡次数未达到5次。

]]

-- local U = require "packages/offline/ofl_util"

local hx__1v3_getLogic = function()
  local hx__1v3_logic = GameLogic:subclass("hx__1v3_logic")

  -- function GameLogic:prepareForStart()
  --   local room = self.room
  --   local players = room.players
  --   self:addTriggerSkill(GameRule)
  --   for _, trig in ipairs(Fk.global_trigger) do
  --     if trig.name ~= "mobile_effect" then  --关闭手杀特效
  --       self:addTriggerSkill(trig)
  --     end
  --   end
  --   self.room:sendLog{ type = "$GameStart" }
  -- end

  function hx__1v3_logic:initialize(room)
    GameLogic.initialize(self, room)
    self.role_table = {
      nil,nil,nil,
      { "lord", "rebel", "rebel", "rebel" },
    }
  end

  function hx__1v3_logic:assignRoles()
    local room = self.room
    local n = #room.players
    local roles = self.role_table[n]
    table.shuffle(roles)

    local players = room.players
    local targets = table.filter(room.players, function(p) return p.id > 0 end)
    local choices = {"当联军！","抢吕布！"}
    local result = room:askToJointChoice(room.players[1], {
      choices = choices,
      players = targets,
      prompt = "请选择你的身份（选择“抢吕布！”的玩家中的随机一名玩家将成为吕布）",
    })
    local lvbus = {}
    for _, p in ipairs(targets) do
      if result[p] == "抢吕布！" then
        table.insert(lvbus, p)
      end
    end
    if #lvbus > 0 then
      local chosen_lord = lvbus[math.random(#lvbus)]
      for _, p in ipairs(players) do
        if p == chosen_lord then
          room:setPlayerProperty(p, "role", "lord")
          room:broadcastProperty(p, "role")
          room:setPlayerProperty(p, "role_shown", true)
        else
          room:setPlayerProperty(p, "role", "rebel")
          room:broadcastProperty(p, "role")
          room:setPlayerProperty(p, "role_shown", true)
        end
      end
    else
      for i = 1, n do
        local p = room.players[i]
        p.role = roles[i]
        room:broadcastProperty(p, "role")
        room:setPlayerProperty(p, "role_shown", true)
      end
    end
    
    local nonlord = table.filter(room.players, function(p) return p.role == "rebel" end)
    nonlord[1]:addBuddy(nonlord[2])
    nonlord[1]:addBuddy(nonlord[3])
    nonlord[2]:addBuddy(nonlord[1])
    nonlord[2]:addBuddy(nonlord[3])
    nonlord[3]:addBuddy(nonlord[1])
    nonlord[3]:addBuddy(nonlord[2])

  end

  --- 分配座位
  function hx__1v3_logic:adjustSeats()
    local player_circle = {}
    local room = self.room
    local players = self.room.players
    local p = 1
    for i = 1, #players do
      if players[i].role == "lord" then
        p = i
        break
      end
    end
    for j = p, #players do
      table.insert(player_circle, players[j])
    end
    for j = 1, p - 1 do
      table.insert(player_circle, players[j])
    end

    self.room:arrangeSeats(player_circle)
  end


  -- function hx__1v3_logic:prepareDrawPile()
  --   local room = self.room
  --   local allCardIds = Fk:getAllCardIds()
  --   local filterCardIds = {}
  --   --卡牌白名单
  --   local white_cards = {"standard","standard_cards","maneuvering","tenyear_token","mobile_derived","ol_token","overseas_token"}
  --   for i = #allCardIds, 1, -1 do
  --     local id = allCardIds[i]
  --     local card = Fk:getCardById(id)
  --     if card then
  --       if card.is_derived or not table.contains(white_cards, card.package.name) then
  --         table.removeOne(allCardIds, id)
  --         table.insert(room.void, id)
  --         room:setCardArea(id, Card.Void, nil)
  --       end
  --       if table.contains(white_cards, card.package.name) then
  --         if not card.is_derived then
  --           table.insert(filterCardIds, id)
  --         end
  --       end
  --     end
  --   end
  --   local seed = math.random(2 << 32 - 1)
  --   table.shuffle(filterCardIds, seed)
  --   room.draw_pile = filterCardIds
  --   for _, id in ipairs(room.draw_pile) do
  --     room:setCardArea(id, Card.DrawPile, nil)
  --   end
  --   room:doBroadcastNotify("PrepareDrawPile", seed)
  -- end

  function hx__1v3_logic:chooseGenerals()
    local room = self.room ---@type Room
    local generalNum = room.settings.generalNum
    local n = room.settings.enableDeputy and 2 or 1
    for _, p in ipairs(room.players) do
      room:setPlayerProperty(p, "role_shown", true)
      room:broadcastProperty(p, "role")
    end

    room:setBanner("@[:]huixiangmode_rule","hx__1v3-intro")

    local lord = room:getLord()
    if lord ~= nil then
      room:setCurrent(lord)
      local players = room.players
      local nonlord = room:getOtherPlayers(lord)
      local generals = table.random(room.general_pile, #room.players * generalNum)
      local lordgenerals = room:getNGenerals(#players * generalNum + 2)

      local req = Request:new(players, "AskForGeneral")
      for i, p in ipairs(players) do
        local arg = table.slice(generals, (i - 1) * generalNum + 1, i * generalNum + 1)
        if p.role == "lord" then
          local count = #lordgenerals -- 吕布多发两个武将
          table.insert(arg, lordgenerals[count])
          table.insert(arg, lordgenerals[count - 1])
          req:setData(p, { arg, 1 })
          req:setDefaultReply(p, table.random(arg, 1))
        else
          req:setData(p, { arg, n })
          req:setDefaultReply(p, table.random(arg, n))
        end
      end

      local lord_result = req:getResult(lord)[1]
      room:setTag("hx__1v3_mode_lordgeneral", lord_result)
      room:prepareGeneral(lord, "sy__lvbu")
      room:setPlayerMark(lord, "@&hx__1v3_mode_lordgeneral", {lord_result})

      for _, p in ipairs(nonlord) do
        local result = req:getResult(p)
        local general, deputy = result[1], result[2]
        room:prepareGeneral(p, general, deputy)
      end

      room:askToChooseKingdom(players)
      room:returnToGeneralPile(lordgenerals)
      room:setTag("SkipNormalDeathProcess", true)
    end
  end

  function hx__1v3_logic:attachSkillToPlayers()
    local room = self.room
    local players = room.players
    local n = room.settings.enableDeputy and 2 or 1
    local addRoleModSkills = function(player, skillName)
      local skill = Fk.skills[skillName]
      if not skill then
        fk.qCritical("Skill: "..skillName.." doesn't exist!")
        return
      end
      if skill:hasTag(Skill.Lord) then return end
      -- if skill:hasTag(Skill.AttachedKingdom) and not
      -- table.contains(skill:getSkeleton().attached_kingdom, player.kingdom) then return end

      room:handleAddLoseSkills(player, skillName, nil, false,true)
      self:trigger(fk.EventAcquireSkill, player, {skill = skill, who = player})
    end
    for _, p in ipairs(room.alive_players) do
      for _, s in ipairs(Fk.generals[p.general]:getSkillNameList(false)) do
        addRoleModSkills(p, s)
      end
      if p.role == "lord" then
        if n == 1 then
          room:handleAddLoseSkills(p, "-kaiju2022", nil, false, true)
        end
        local lord_result = room:getTag("hx__1v3_mode_lordgeneral")
        for _, s in ipairs(Fk.generals[lord_result]:getSkillNameList(false)) do
          addRoleModSkills(p, s)
        end
      end
      local deputy = Fk.generals[p.deputyGeneral]
      if deputy then
        if p.role == "lord" then
          -- U.sgshLoseDeputy(p)
          --room:handleAddLoseSkills(p, "huixiang__fenghuo", nil, false)
        else
          for _, s in ipairs(deputy:getSkillNameList(true)) do
            addRoleModSkills(p, s)
          end
        end
      end
    end
  end
  return hx__1v3_logic
end

local hx__1v3_mode = fk.CreateGameMode{
  name = "hx__1v3_mode",
  minPlayer = 4,
  maxPlayer = 4,
  rule = "#hx__1v3_rule&",
  logic = hx__1v3_getLogic,
  is_counted = function(self, room)
    return #room.players >= 4
  end,
  build_draw_pile = function(self)
    local allCardIds = Fk:getAllCardIds()
    local filterCardIds = {}
    local void = {}
    --卡牌白名单
    local white_cards = {"standard","standard_cards","maneuvering","tenyear_token","mobile_derived","ol_token","overseas_token"}
    for i = #allCardIds, 1, -1 do
      local id = allCardIds[i]
      local card = Fk:getCardById(id)
      if card then
        if card.is_derived or not table.contains(white_cards, card.package.name) then
          table.removeOne(allCardIds, id)
          table.insert(void, id)
        end
        if table.contains(white_cards, card.package.name) then
          if not card.is_derived then
            table.insert(filterCardIds, id)
          end
        end
      end
    end
    return filterCardIds, void
  end,
  surrender_func = function(self, playedTime)
    local surrenderJudge = { { text = "time limitation: 1 min", passed = playedTime >= 60 },
    { text = "2v2: left you alive", passed = not table.find(Fk:currentRoom().players, function(p)
      return p ~= Self and p.role == Self.role and not (p.dead and p.rest == 0)
    end) } }
    return surrenderJudge
  end,
  winner_getter = function(self, victim)
    if not victim.surrendered and victim.rest > 0 then
      return ""
    end
    local room = victim.room
    local alive = table.filter(room.players, function(p) ---@type Player[]
      return not p.surrendered and not (p.dead and p.rest == 0)
    end)
    local winner = alive[1].role
    for _, p in ipairs(alive) do
      if p.role ~= winner then
        return ""
      end
    end
    return winner
  end,
  get_adjusted = function (self, player)
    if player.role == "lord" then
      return {hp = 10, maxHp = 10}
    end
    return {}
  end
}

Fk:loadTranslationTable{
  ["hx__1v3_mode"] = "虎牢关2022",
  ["#hx__1v3_rule&"] = "虎牢关2022规则",
  ["@huixiangmode_dead"] = "联军阵亡次数",
  ["@[:]huixiangmode_rule"]="模式",
  ["@&hx__1v3_mode_lordgeneral"] = "吕布武将",
  ["hx__1v3-intro"] = "虎牢关2022(点击查看)",
  [":hx__1v3-intro"] = [[
  <br/>注意，本模式为PVP模式！
  <br/><b>吕布胜利条件：</b>
  <br/>使三名联军同时处于休整状态。或联军累计阵亡5次。
  <br/><b>联军胜利条件：</b>
  <br/>击败吕布或吕布阵亡。联军一回合内未全部处于休整状态，且累计阵亡次数未达到5次。
  <br/>联军阵亡时若仍有联军在场则改为休整一轮。
  <br/>（开启双将 吕布 将不再失去技能【再临】）]],
  [":hx__1v3_mode"] = desc_hx__1v3,
}

return hx__1v3_mode
